<template>
  <div class="food-form-mobile">
    <n-form ref="formRef" :model="formData" :rules="formRules" label-placement="top">
      <!-- 基本信息 -->
      <n-card title="基本信息" size="small" style="margin-bottom: 16px;">
        <n-form-item label="中文名称" path="name_zh">
          <n-input v-model:value="formData.name_zh" placeholder="请输入中文名称（必填）" :maxlength="100" show-count />
        </n-form-item>

        <n-form-item label="英文名称">
          <n-input v-model:value="formData.name_en" placeholder="请输入英文名称（可选）" :maxlength="100" show-count />
        </n-form-item>

        <n-form-item label="其他名称">
          <n-dynamic-input v-model:value="formData.other_names" placeholder="添加其他常用名称" :max="5" />
        </n-form-item>
      </n-card>

      <!-- 宏量营养素 -->
      <n-card size="small" style="margin-bottom: 16px;">
        <div class="nutrient-grid">
          <NutrientInput v-model:value="formData.energy_kcal" v-model:rich="formData.energy_rich" label="能量"
            unit="kcal/100g" :precision="1" :max="900" />
          <NutrientInput v-model:value="formData.protein_g" v-model:rich="formData.protein_rich" label="蛋白质"
            unit="g/100g" :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.fat_g" v-model:rich="formData.fat_rich" label="脂肪" unit="g/100g"
            :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.omega3_g" v-model:rich="formData.omega3_rich" label="Omega-3"
            unit="g/100g" :precision="2" :max="50" />
          <NutrientInput v-model:value="formData.carb_g" v-model:rich="formData.carb_rich" label="碳水化合物" unit="g/100g"
            :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.sugars_g" v-model:rich="formData.sugars_rich" label="糖" unit="g/100g"
            :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.resistant_starch_g" v-model:rich="formData.resistant_starch_rich"
            label="抗性淀粉" unit="g/100g" :precision="1" :max="50" />
          <NutrientInput v-model:value="formData.fiber_g" v-model:rich="formData.fiber_rich" label="膳食纤维" unit="g/100g"
            :precision="1" :max="100" />
        <!-- </div> -->
        <!-- </n-card> -->

        <!-- 矿物质 -->
        <!-- <div class="nutrient-grid"> -->
          <NutrientInput v-model:value="formData.sodium_mg" v-model:rich="formData.sodium_rich" label="钠" unit="mg/100g"
            :precision="1" :max="5000" />
          <NutrientInput v-model:value="formData.magnesium_mg" v-model:rich="formData.magnesium_rich" label="镁"
            unit="mg/100g" :precision="1" :max="1000" />
          <NutrientInput v-model:value="formData.calcium_mg" v-model:rich="formData.calcium_rich" label="钙"
            unit="mg/100g" :precision="1" :max="2000" />
          <NutrientInput v-model:value="formData.iron_mg" v-model:rich="formData.iron_rich" label="铁" unit="mg/100g"
            :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.zinc_mg" v-model:rich="formData.zinc_rich" label="锌" unit="mg/100g"
            :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.selenium_mcg" v-model:rich="formData.selenium_rich" label="硒"
            unit="mcg/100g" :precision="1" :max="1000" />
        <!-- </div> -->
        <!-- <n-card title="矿物质" size="small" style="margin-bottom: 16px;">
        
      </n-card> -->

        <!-- 维生素 -->
        <!-- <div class="nutrient-grid"> -->
          <NutrientInput v-model:value="formData.vitamin_a_ug" v-model:rich="formData.vitamin_a_rich" label="维生素A"
            unit="μg/100g" :precision="1" :max="10000" />
          <NutrientInput v-model:value="formData.vitamin_c_mg" v-model:rich="formData.vitamin_c_rich" label="维生素C"
            unit="mg/100g" :precision="1" :max="1000" />
          <NutrientInput v-model:value="formData.vitamin_d_mcg" v-model:rich="formData.vitamin_d_rich" label="维生素D"
            unit="mcg/100g" :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.vitamin_e_mg" v-model:rich="formData.vitamin_e_rich" label="维生素E"
            unit="mg/100g" :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.thiamin_mg" v-model:rich="formData.thiamin_rich" label="维生素B1"
            unit="mg/100g" :precision="2" :max="10" />
          <NutrientInput v-model:value="formData.riboflavin_mg" v-model:rich="formData.riboflavin_rich" label="维生素B2"
            unit="mg/100g" :precision="2" :max="10" />
          <NutrientInput v-model:value="formData.vitamin_b6_mg" v-model:rich="formData.vitamin_b6_rich" label="维生素B6"
            unit="mg/100g" :precision="2" :max="10" />
          <NutrientInput v-model:value="formData.vitamin_b12_mcg" v-model:rich="formData.vitamin_b12_rich"
            label="维生素B12" unit="mcg/100g" :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.niacin_mg" v-model:rich="formData.niacin_rich" label="烟酸"
            unit="mg/100g" :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.folate_mcg" v-model:rich="formData.folate_rich" label="叶酸"
            unit="mcg/100g" :precision="1" :max="1000" />
          <!-- 新增营养素 -->
          <NutrientInput v-model:value="formData.cholesterol_mg" v-model:rich="formData.cholesterol_rich" label="胆固醇"
            unit="mg/100g" :precision="1" :max="1000" />
          <NutrientInput v-model:value="formData.ash_g" v-model:rich="formData.ash_rich" label="灰分"
            unit="g/100g" :precision="1" :max="20" />
          <NutrientInput v-model:value="formData.thiamine_b1_mg" v-model:rich="formData.thiamine_b1_rich" label="硫胺素(B1)"
            unit="mg/100g" :precision="2" :max="10" />
          <NutrientInput v-model:value="formData.riboflavin_b2_g" v-model:rich="formData.riboflavin_b2_rich" label="核黄素(B2)"
            unit="g/100g" :precision="3" :max="1" />
          <NutrientInput v-model:value="formData.niacin_nicotinic_mg" v-model:rich="formData.niacin_nicotinic_rich" label="烟碱"
            unit="mg/100g" :precision="1" :max="100" />
          <NutrientInput v-model:value="formData.phosphorus_mg" v-model:rich="formData.phosphorus_rich" label="磷"
            unit="mg/100g" :precision="1" :max="2000" />
          <NutrientInput v-model:value="formData.potassium_mg" v-model:rich="formData.potassium_rich" label="钾"
            unit="mg/100g" :precision="1" :max="5000" />
          <NutrientInput v-model:value="formData.copper_mg" v-model:rich="formData.copper_rich" label="铜"
            unit="mg/100g" :precision="2" :max="10" />
          <NutrientInput v-model:value="formData.manganese_mg" v-model:rich="formData.manganese_rich" label="锰"
            unit="mg/100g" :precision="2" :max="10" />
          <NutrientInput v-model:value="formData.iodine_mg" v-model:rich="formData.iodine_rich" label="碘"
            unit="mg/100g" :precision="3" :max="1" />
          <NutrientInput v-model:value="formData.carotene_ug" v-model:rich="formData.carotene_rich" label="胡萝卜素"
            unit="μg/100g" :precision="1" :max="50000" />
          <NutrientInput v-model:value="formData.retinol_ug" v-model:rich="formData.retinol_rich" label="视黄醇"
            unit="μg/100g" :precision="1" :max="10000" />
          <NutrientInput v-model:value="formData.purine_mg" v-model:rich="formData.purine_rich" label="嘌呤"
            unit="mg/100g" :precision="1" :max="1000" />
        </div>
      </n-card>
      <n-card title="自定义营养素" size="small" style="margin-bottom: 16px;">
        <!-- 自定义营养素 -->
        <!-- <n-divider>自定义营养素</n-divider> -->
        <div v-for="(nutrient, index) in formData.other_nutrients" :key="index" class="custom-nutrient-mobile">
          <div class="custom-nutrient-header">
            <span class="nutrient-index">营养素 {{ index + 1 }}</span>
            <n-button quaternary type="error" size="small" @click="removeOtherNutrient(index)">
              <n-icon>
                <Close />
              </n-icon>
            </n-button>
          </div>

          <div class="custom-nutrient-content">
            <div class="nutrient-select-row">
              <n-select v-model:value="nutrient.nutrient_id" placeholder="选择营养素" :options="nutrientOptions"
                @update:value="updateNutrientInfo(index, $event)" style="width: 100%;" />
            </div>

            <div class="nutrient-input-row">
              <div class="amount-input">
                <label class="input-label">含量</label>
                <n-input-number v-model:value="nutrient.amount" placeholder="输入含量" :precision="2" :min="0" size="medium"
                  style="width: 100%;" :show-button="true" clearable />
              </div>

              <div class="unit-input">
                <label class="input-label">单位</label>
                <n-input v-model:value="nutrient.unit" placeholder="如: mg" style="width: 100%;" />
              </div>
            </div>

            <div class="rich-switch-row">
              <div class="rich-switch-container">
                <n-switch v-model:value="nutrient.rich" size="medium" />
                <span class="rich-label">富含此营养素</span>
                <n-tag v-if="nutrient.rich" type="success" size="small" style="margin-left: 8px;">
                  <n-icon :size="12" style="margin-right: 4px;">
                    <CheckmarkCircle />
                  </n-icon>
                  富含
                </n-tag>
              </div>
            </div>
          </div>
        </div>

        <n-button dashed @click="addOtherNutrient" style="width: 100%; margin-top: 16px;" size="large">
          <n-icon>
            <Add />
          </n-icon>
          添加自定义营养素
        </n-button>
      </n-card>

      <!-- 操作按钮 -->
      <div class="form-actions">
        <n-space>
          <n-button type="primary" @click="handleSubmit" :loading="loading" block>
            {{ isEditing ? '保存修改' : '创建食物' }}
          </n-button>
          <n-button v-if="showCancelButton" @click="handleCancel" block>
            取消
          </n-button>
        </n-space>
      </div>
    </n-form>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, watch } from 'vue'
  import type { FormInst, FormRules } from 'naive-ui'
  import { Add, Close, CheckmarkCircle } from '@vicons/ionicons5'
  import type { Food, Nutrient, CreateFoodForm } from '@/types'
  import NutrientInput from './NutrientInput.vue'

  interface Props {
    food?: Food | null
    nutrients?: Nutrient[]
    showCancelButton?: boolean
  }

  interface Emits {
    (e: 'submit', data: CreateFoodForm): void
    (e: 'cancel'): void
  }

  const props = withDefaults(defineProps<Props>(), {
    food: null,
    nutrients: () => [],
    showCancelButton: true
  })

  const emit = defineEmits<Emits>()

  // 响应式数据
  const formRef = ref<FormInst | null>(null)
  const loading = ref(false)

  const formData = reactive<CreateFoodForm>({
    name_zh: '',
    name_en: '',
    other_names: [],
    other_langs: {},
    // 宏量营养素
    energy_kcal: undefined,
    energy_rich: false,
    protein_g: undefined,
    protein_rich: false,
    fat_g: undefined,
    fat_rich: false,
    omega3_g: undefined,
    omega3_rich: false,
    carb_g: undefined,
    carb_rich: false,
    sugars_g: undefined,
    sugars_rich: false,
    resistant_starch_g: undefined,
    resistant_starch_rich: false,
    fiber_g: undefined,
    fiber_rich: false,
    // 矿物质
    sodium_mg: undefined,
    sodium_rich: false,
    magnesium_mg: undefined,
    magnesium_rich: false,
    calcium_mg: undefined,
    calcium_rich: false,
    iron_mg: undefined,
    iron_rich: false,
    zinc_mg: undefined,
    zinc_rich: false,
    selenium_mcg: undefined,
    selenium_rich: false,
    // 维生素
    vitamin_a_ug: undefined,
    vitamin_a_rich: false,
    vitamin_c_mg: undefined,
    vitamin_c_rich: false,
    vitamin_d_mcg: undefined,
    vitamin_d_rich: false,
    vitamin_e_mg: undefined,
    vitamin_e_rich: false,
    thiamin_mg: undefined,
    thiamin_rich: false,
    riboflavin_mg: undefined,
    riboflavin_rich: false,
    vitamin_b6_mg: undefined,
    vitamin_b6_rich: false,
    vitamin_b12_mcg: undefined,
    vitamin_b12_rich: false,
    niacin_mg: undefined,
    niacin_rich: false,
    folate_mcg: undefined,
    folate_rich: false,
    // 新增营养素
    cholesterol_mg: undefined,
    cholesterol_rich: false,
    ash_g: undefined,
    ash_rich: false,
    thiamine_b1_mg: undefined,
    thiamine_b1_rich: false,
    riboflavin_b2_g: undefined,
    riboflavin_b2_rich: false,
    niacin_nicotinic_mg: undefined,
    niacin_nicotinic_rich: false,
    phosphorus_mg: undefined,
    phosphorus_rich: false,
    potassium_mg: undefined,
    potassium_rich: false,
    copper_mg: undefined,
    copper_rich: false,
    manganese_mg: undefined,
    manganese_rich: false,
    iodine_mg: undefined,
    iodine_rich: false,
    carotene_ug: undefined,
    carotene_rich: false,
    retinol_ug: undefined,
    retinol_rich: false,
    purine_mg: undefined,
    purine_rich: false,
    other_nutrients: []
  })

  const formRules: FormRules = {
    name_zh: [
      { required: true, message: '请输入中文名称', trigger: 'blur' }
    ]
  }

  // 方法 - 先定义 resetForm 函数
  const resetForm = () => {
    Object.assign(formData, {
      name_zh: '',
      name_en: '',
      other_names: [],
      other_langs: {},
      // 宏量营养素
      energy_kcal: undefined,
      energy_rich: false,
      protein_g: undefined,
      protein_rich: false,
      fat_g: undefined,
      fat_rich: false,
      omega3_g: undefined,
      omega3_rich: false,
      carb_g: undefined,
      carb_rich: false,
      sugars_g: undefined,
      sugars_rich: false,
      resistant_starch_g: undefined,
      resistant_starch_rich: false,
      fiber_g: undefined,
      fiber_rich: false,
      // 矿物质
      sodium_mg: undefined,
      sodium_rich: false,
      magnesium_mg: undefined,
      magnesium_rich: false,
      calcium_mg: undefined,
      calcium_rich: false,
      iron_mg: undefined,
      iron_rich: false,
      zinc_mg: undefined,
      zinc_rich: false,
      selenium_mcg: undefined,
      selenium_rich: false,
      // 维生素
      vitamin_a_ug: undefined,
      vitamin_a_rich: false,
      vitamin_c_mg: undefined,
      vitamin_c_rich: false,
      vitamin_d_mcg: undefined,
      vitamin_d_rich: false,
      vitamin_e_mg: undefined,
      vitamin_e_rich: false,
      thiamin_mg: undefined,
      thiamin_rich: false,
      riboflavin_mg: undefined,
      riboflavin_rich: false,
      vitamin_b6_mg: undefined,
      vitamin_b6_rich: false,
      vitamin_b12_mcg: undefined,
      vitamin_b12_rich: false,
      niacin_mg: undefined,
      niacin_rich: false,
      folate_mcg: undefined,
      folate_rich: false,
      // 新增营养素
      cholesterol_mg: undefined,
      cholesterol_rich: false,
      ash_g: undefined,
      ash_rich: false,
      thiamine_b1_mg: undefined,
      thiamine_b1_rich: false,
      riboflavin_b2_g: undefined,
      riboflavin_b2_rich: false,
      niacin_nicotinic_mg: undefined,
      niacin_nicotinic_rich: false,
      phosphorus_mg: undefined,
      phosphorus_rich: false,
      potassium_mg: undefined,
      potassium_rich: false,
      copper_mg: undefined,
      copper_rich: false,
      manganese_mg: undefined,
      manganese_rich: false,
      iodine_mg: undefined,
      iodine_rich: false,
      carotene_ug: undefined,
      carotene_rich: false,
      retinol_ug: undefined,
      retinol_rich: false,
      purine_mg: undefined,
      purine_rich: false,
      other_nutrients: []
    })
  }

  // 计算属性
  const isEditing = computed(() => !!props.food)

  const nutrientOptions = computed(() => {
    return props.nutrients.map(n => ({
      label: n.nutrient_name_zh,
      value: n.id
    }))
  })

  // 监听props变化
  watch(() => props.food, (newFood) => {
    if (newFood) {
      // 编辑模式，填充表单数据
      Object.assign(formData, {
        name_zh: newFood.name_zh,
        name_en: newFood.name_en || '',
        other_names: newFood.other_names || [],
        other_langs: newFood.other_langs || {},
        // 宏量营养素
        energy_kcal: newFood.energy_kcal,
        energy_rich: newFood.energy_rich,
        protein_g: newFood.protein_g,
        protein_rich: newFood.protein_rich,
        fat_g: newFood.fat_g,
        fat_rich: newFood.fat_rich,
        omega3_g: newFood.omega3_g,
        omega3_rich: newFood.omega3_rich,
        carb_g: newFood.carb_g,
        carb_rich: newFood.carb_rich,
        sugars_g: newFood.sugars_g,
        sugars_rich: newFood.sugars_rich,
        resistant_starch_g: newFood.resistant_starch_g,
        resistant_starch_rich: newFood.resistant_starch_rich,
        fiber_g: newFood.fiber_g,
        fiber_rich: newFood.fiber_rich,
        // 矿物质
        sodium_mg: newFood.sodium_mg,
        sodium_rich: newFood.sodium_rich,
        magnesium_mg: newFood.magnesium_mg,
        magnesium_rich: newFood.magnesium_rich,
        calcium_mg: newFood.calcium_mg,
        calcium_rich: newFood.calcium_rich,
        iron_mg: newFood.iron_mg,
        iron_rich: newFood.iron_rich,
        zinc_mg: newFood.zinc_mg,
        zinc_rich: newFood.zinc_rich,
        selenium_mcg: newFood.selenium_mcg,
        selenium_rich: newFood.selenium_rich,
        // 维生素
        vitamin_a_ug: newFood.vitamin_a_ug,
        vitamin_a_rich: newFood.vitamin_a_rich,
        vitamin_c_mg: newFood.vitamin_c_mg,
        vitamin_c_rich: newFood.vitamin_c_rich,
        vitamin_d_mcg: newFood.vitamin_d_mcg,
        vitamin_d_rich: newFood.vitamin_d_rich,
        vitamin_e_mg: newFood.vitamin_e_mg,
        vitamin_e_rich: newFood.vitamin_e_rich,
        thiamin_mg: newFood.thiamin_mg,
        thiamin_rich: newFood.thiamin_rich,
        riboflavin_mg: newFood.riboflavin_mg,
        riboflavin_rich: newFood.riboflavin_rich,
        vitamin_b6_mg: newFood.vitamin_b6_mg,
        vitamin_b6_rich: newFood.vitamin_b6_rich,
        vitamin_b12_mcg: newFood.vitamin_b12_mcg,
        vitamin_b12_rich: newFood.vitamin_b12_rich,
        niacin_mg: newFood.niacin_mg,
        niacin_rich: newFood.niacin_rich,
        folate_mcg: newFood.folate_mcg,
        folate_rich: newFood.folate_rich,
        // 新增营养素
        cholesterol_mg: newFood.cholesterol_mg,
        cholesterol_rich: newFood.cholesterol_rich,
        ash_g: newFood.ash_g,
        ash_rich: newFood.ash_rich,
        thiamine_b1_mg: newFood.thiamine_b1_mg,
        thiamine_b1_rich: newFood.thiamine_b1_rich,
        riboflavin_b2_g: newFood.riboflavin_b2_g,
        riboflavin_b2_rich: newFood.riboflavin_b2_rich,
        niacin_nicotinic_mg: newFood.niacin_nicotinic_mg,
        niacin_nicotinic_rich: newFood.niacin_nicotinic_rich,
        phosphorus_mg: newFood.phosphorus_mg,
        phosphorus_rich: newFood.phosphorus_rich,
        potassium_mg: newFood.potassium_mg,
        potassium_rich: newFood.potassium_rich,
        copper_mg: newFood.copper_mg,
        copper_rich: newFood.copper_rich,
        manganese_mg: newFood.manganese_mg,
        manganese_rich: newFood.manganese_rich,
        iodine_mg: newFood.iodine_mg,
        iodine_rich: newFood.iodine_rich,
        carotene_ug: newFood.carotene_ug,
        carotene_rich: newFood.carotene_rich,
        retinol_ug: newFood.retinol_ug,
        retinol_rich: newFood.retinol_rich,
        purine_mg: newFood.purine_mg,
        purine_rich: newFood.purine_rich,
        other_nutrients: newFood.other_nutrients || []
      })
    } else {
      // 重置表单
      resetForm()
    }
  }, { immediate: true })

  // 方法
  const addOtherNutrient = () => {
    formData.other_nutrients?.push({
      nutrient_id: undefined,
      name_zh: '',
      amount: undefined,
      unit: '',
      rich: false
    })
  }

  const removeOtherNutrient = (index: number) => {
    formData.other_nutrients?.splice(index, 1)
  }

  const updateNutrientInfo = (index: number, nutrientId: number) => {
    const nutrient = props.nutrients.find(n => n.id === nutrientId)
    if (nutrient && formData.other_nutrients?.[index]) {
      formData.other_nutrients[index].name_zh = nutrient.nutrient_name_zh
      formData.other_nutrients[index].unit = nutrient.unit_zh
    }
  }

  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      loading.value = true
      emit('submit', { ...formData })
    } catch (error) {
      console.error('Form validation failed:', error)
    } finally {
      loading.value = false
    }
  }

  const handleCancel = () => {
    emit('cancel')
  }
</script>

<style scoped>
  .food-form-mobile {
    padding: 16px;
  }

  .nutrient-grid {
    display: grid;
    grid-template-columns: 1fr;
    gap: 12px;
  }

  /* 自定义营养素样式 */
  .custom-nutrient-mobile {
    margin-bottom: 16px;
    padding: 16px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    background: #fafafa;
  }

  .custom-nutrient-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
  }

  .nutrient-index {
    font-weight: 500;
    color: #333;
    font-size: 14px;
  }

  .custom-nutrient-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .nutrient-select-row {
    width: 100%;
  }

  .nutrient-input-row {
    display: grid;
    grid-template-columns: 2fr 1fr;
    gap: 12px;
  }

  .amount-input,
  .unit-input {
    display: flex;
    flex-direction: column;
    gap: 4px;
  }

  .input-label {
    font-size: 12px;
    color: #666;
    font-weight: 500;
  }

  .rich-switch-row {
    display: flex;
    align-items: center;
  }

  .rich-switch-container {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .rich-label {
    font-size: 14px;
    color: #333;
  }

  .form-actions {
    margin-top: 24px;
    padding-top: 16px;
    border-top: 1px solid #e0e0e0;
  }
</style>
